Given a string s
, return the number of unique palindromes of length three that are a subsequence ofs
.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.
A palindrome is a string that reads the same forwards and backwards.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
- For example,
"ace"
is a subsequence of"abcde"
.
Input: s = "aabca" Output: 3 Explanation: The 3 palindromic subsequences of length 3 are: - "aba" (subsequence of "aabca") - "aaa" (subsequence of "aabca") - "aca" (subsequence of "aabca")
Input: s = "adc" Output: 0 Explanation: There are no palindromic subsequences of length 3 in "adc".
Input: s = "bbcbaba" Output: 4 Explanation: The 4 palindromic subsequences of length 3 are: - "bbb" (subsequence of "bbcbaba") - "bcb" (subsequence of "bbcbaba") - "bab" (subsequence of "bbcbaba") - "aba" (subsequence of "bbcbaba")
3 <= s.length <= 105
s
consists of only lowercase English letters.
implSolution{pubfncount_palindromic_subsequence(s:String) -> i32{let s = s.as_bytes();letmut ret = 0;for c inb'a'..=b'z'{letmut mask = 0_i32;for i in s.iter().position(|&x| x == c).unwrap_or(0) + 1 ..s.iter().rposition(|&x| x == c).unwrap_or(0){ mask |= 1 << (s[i] - b'a');} ret += mask.count_ones();} ret asi32}}